import api from '../../utils/api';
import util from '../../utils/common';
import { UserInfoType } from '../../types/index';

Page({
  data: {
    userName: '游客',
    userId: '',
    roles: '',
    introductionText: '点击这里授权登录',
    mineData: [
      {
        id: 'personalInfo',
        icon: '../../images/edit.svg',
        text: '修改密码'
      },
      {
        id: 'comment',
        icon: '../../images/news.svg',
        text: '我的评论'
      },
      {
        id: 'create',
        icon: '../../images/create.svg',
        text: '立即创作'
      },
      {
        id: 'loginout',
        icon: '../../images/loginout.svg',
        text: '退出登录',
        isLast: true
      }
    ]
  },
  onShow() {
    // 页面显示
    const user = my.getStorageSync({key: 'user'}); 
    if (user) {
      this.getInfo();
    }
  },
  async getInfo () {
    const res: UserInfoType = await api.getUserInfo();
    if (res?.id) {
      this.setData({
        introductionText: '创作者',
        userName: res.name,
        userId: res.id
      })
    }   
  },
  // 跳转登录页
  getProfile () {
    // 未登录
    if (!this.data.userId) {
      my.navigateTo({
        url: '/pages/login/login'
      })
    }
  },
  // 点击标签
  bindTag (e) {  
    // 未登录
    if (!this.data.userId) {
      util.showToast('您目前没有登录，请先去登录。');
      return ;
    } 

    // 获取当前操作的值
    const value = e.currentTarget.id;

    // 定义路由映射表
    const routes = {
      create: `/pages/create/create?userId=${this.data.userId}`,
      personalInfo: `/pages/personal/personal`,
      comment: `/pages/myComment/myComment?userId=${this.data.userId}`
    };
    
    // 处理页面跳转
    if (routes[value]) {
      my.navigateTo({
        url: routes[value]
      });
    }

    // 退出登录
    if (value == 'loginout') {
      const that = this;
      my.showModal({
        content: '您确定要退出登录吗？',
        success (res) {
          if (res.confirm) {
            api.loginout();
            that.setData({
              introductionText: '点击这里授权登录',
              userName: '游客',
              userId: ''
            })
          }
        }
      }) 
    }
  }
});
